package com;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.nio.file.Files;
import java.nio.file.Paths;

public class LicenseSigner {

    // 私钥（不可泄露）包检道项目 UtensilXlsxUtil  810行5670行
    private static final String PRIVATE_KEY_BASE64 = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCqRCpdayZr/wz0LEMbgFi3PsmLPEuBj5/pnjBBxi8ppU11nrfEz76uf1D3kjs8pYOpK1JFBfgDmnH8b6JZi6ldURKVJ/Wv1Mo64G4rr235cF8y+MYf4QCoaGhwat+z4bxt7wKV0gk7LdltrJRrva+GWAgACT4h/Quql8R0kEJqpQVWMQoeiCnYuoHVXvJ3lcJrP4y6VuZB52Kq8JJZC36ZTK8uB0f6L04Sy/Rxw1LZfid184kLv5PZUrTFuo92MqeAHRwKRky865nwatupNF2Cui+fGUk+v16eEgQS8Kj2LNqLRdrH2BPtihrELD+tJUq17aB2CtX9pg/owvtkqQfLAgMBAAECggEBAKWNsA+zfuFlVkgYvYuBCUHrx/YdQ2GPsDJsgImD1RnOQ/nIwPCZ+tMasjR2uCho2xLjL5QzkIqYYprMRPSCisRUbxgeiZJU+emzjQvnAKyYKcibAbG/im81Tc9461ixdhECY+YfGqCzHQW513rHLmMXN3gphINx0yUlenzIQ/wCMBw4gw6gLLOG1mzDgPvaRpTMiU2Ld2mcs/3XRWqtDfSLPhu1Htwh4u+9SqLnxnCGoFsjaHWBNorxv76sbF4OnVt8dfcX2OQcXq7Hre9B4EN/fBiJVR8Q/rgvG1NlktlFw9xX1UkaCVEU3T3zjoSNkvLdIJckTLnK8JIlS1M64wkCgYEA27sPNuKjvKBARuzyVkqboitMP2Yz8+KMErkWdo9lQvSsNFTIdC+sGtQF8bu0K1Edo5REtHwlwTiPLL5N4dBZ6+8Ca1QLWgLpZ4hE4asIZWQVXPA9JyiaWJoPMv0kiPeoeo9Q84ZcMN1lvrGw9zaMM0zxDaktdoglt8hwEYORl/UCgYEAxl7v5mJgwF2cre1k4KqtEhu5otWcHIGsOVxeMfjPxCbJEaZFmjRulCJRQXlZzdwBt6N2a3Zgg7jKZfjO/+wI0rsM79vi0JQ3SZpFlytdNlbpkfV1sfWo2M6qMO0KlyFlyTggVTIl9RaufgH/wSlGZUDWJ0DyldFhXmSeuUyFCL8CgYEAvIJ6JgtAkBYnrvGfYpq1dOaSjp2/GpAUvgdely6koFHK30aRhuRTUdzukJoJk1QPCoSsgO81cNR2ONu3c3DNhJVTzQKYjouK9NC6z6RtGpdHoKlWvZ6e9D6PpZ351ywptaP4vkRaGW4H2RcXDLAWjfiHocGviE57lXV3d/8ZTHUCgYEAxMs6Q9wlD7HO1d1Ezn2D5QsMRraTgNRD/0PbTsf/liDEKHZDZo/Ng7fn1ISGyusP6RaJTGLLrOGOKUuET+/hcO2QEAScJ0Bi+OnLUAT9HANtBBf3Au0q7KtZu9/tObEwQUclDGALt/EgenGRQBeqdpiz241bG7X0WqiHrlxzPhECgYBDDSG+EOU95JLpz6VEtF10+8Tg5bJrDroB033/6ccQE56HRAXG1+Wo3G3Ij8NqqN6K/gihIkvBPDNz7LR1A1kEHyyqgtlb4AGF2D/HjqjOgtqaF0qKDSMhpZgKmOYGrx/5URYwTpmNAVNAxTaIawrcsodn9v/DJoMiAhBkRH51pw==";
    // 公钥（用于项目验证）包检道项目
    private static final String PUBLIC_KEY_BASE64 = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqkQqXWsma/8M9CxDG4BYtz7JizxLgY+f6Z4wQcYvKaVNdZ63xM++rn9Q95I7PKWDqStSRQX4A5px/G+iWYupXVESlSf1r9TKOuBuK69t+XBfMvjGH+EAqGhocGrfs+G8be8CldIJOy3ZbayUa72vhlgIAAk+If0LqpfEdJBCaqUFVjEKHogp2LqB1V7yd5XCaz+MulbmQediqvCSWQt+mUyvLgdH+i9OEsv0ccNS2X4ndfOJC7+T2VK0xbqPdjKngB0cCkZMvOuZ8GrbqTRdgrovnxlJPr9enhIEEvCo9izai0Xax9gT7YoaxCw/rSVKte2gdgrV/aYP6ML7ZKkHywIDAQAB";
    public static void main(String[] args) {
        try {
            // 1. 从 Base64 字符串加载私钥
            PrivateKey privateKey = getPrivateKeyFromBase64(PRIVATE_KEY_BASE64);

            // 2. 构建授权数据
            Map<String, Object> data = new HashMap<>();
            data.put("licenseId", "LIC-2025");
            data.put("issuedTo", "Your Company");
            data.put("expiryDate", "2025-09-09T12:05:05");

            ObjectMapper mapper = new ObjectMapper();
            String jsonData = mapper.writeValueAsString(data); // 标准化 JSON 字符串

            // 3. 使用私钥签名
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(privateKey);
            signature.update(jsonData.getBytes());
            byte[] signBytes = signature.sign();
            String signatureB64 = Base64.getEncoder().encodeToString(signBytes);

            // 4. 构建 license.dat 内容
            Map<String, String> license = new HashMap<>();
            license.put("data", jsonData);
            license.put("signature", signatureB64);

            String licenseJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(license);

            // 5. 写入 D:\license.dat
            Files.write(Paths.get("D:/license.dat"), licenseJson.getBytes());

            System.out.println("✅ 授权文件已生成：D:\\license.dat");
            System.out.println(licenseJson);

        } catch (Exception e) {
            System.err.println("❌ 授权文件生成失败！");
            e.printStackTrace();
        }
    }

    /**
     * 从 Base64 编码的私钥字符串解析出 PrivateKey 对象
     */
    private static PrivateKey getPrivateKeyFromBase64(String base64PrivateKey) throws Exception {
        byte[] decoded = Base64.getDecoder().decode(base64PrivateKey.trim());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decoded);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }
}